package com.um2.mauction.java;

import java.io.IOException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import com.um2.mauction.entity.Enchere;
import com.um2.mauction.entity.Vente;
import com.um2.mauction.session.impl.VenteManagerBean;
import com.um2.mauction.session.remote.VenteManagerRemote;

public class PlaceBidInitAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		ActionForward resultat = mapping.findForward("succes");
		ActionErrors errors = new ActionErrors();

		// Récuparation données du bean
		// DynaActionForm formulaire = (DynaActionForm) form;

		// float oldBid = Float.parseFloat((String) formulaire.get("oldBid"));
		// float newBid =Float.parseFloat((String) formulaire.get("old")) ;
		int id_Sale = 2;
		float lastbid = 0;

		VenteManagerRemote salemanager = null;

		try {
			InitialContext ic = new InitialContext();

			salemanager = (VenteManagerRemote) ic
					.lookup(VenteManagerBean.RemoteJNDIName);

			Vente v = salemanager.getVente(id_Sale);

			if (v == null) {
				errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("placebid.vente.null"));
				resultat = new ActionForward(mapping.getInput());
			} else {

				Enchere e = salemanager.getLastEnchereOfVente(id_Sale);

				
				if (e != null)
					lastbid = e.getAmount();
				else
					lastbid = v.getMontantInitial();

			
			System.out.println("lb: "+ lastbid);
			
			HttpSession session = request.getSession();	
			session.setAttribute("txtOldBid", lastbid);
			}
			
		} catch (NamingException e) {
			errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("ajoutprod.statefulBean.notBound"));
			resultat = new ActionForward(mapping.getInput());
		}

		if (!errors.isEmpty()) {
			saveErrors(request, errors);
		}
		return resultat;

	}
}
